<template>
  <div class="login-wrap">
    <div class="fold-icon" @click="handleFold">
      <el-icon color="#FFF" size="20px">
        <Fold />
      </el-icon>
    </div>
    <div class="ms-login">
      <div class="ms-title">IWu招聘-管理员登录</div>
      <el-form :model="loginUser" :rules="loginRules" ref="loginForm" label-width="0px" class="ms-content">
        <el-form-item prop="email">
          <el-input v-model="loginUser.email" placeholder="请输入邮箱">
            <el-button slot="prepend" icon="el-icon-lx-people"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="loginUser.password"
            @keyup.enter.native="handleLogin(loginForm)">
            <el-button slot="prepend" icon="el-icon-lx-lock"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item prop="code_1">
          <div class="codeItem">
            <el-input type="text" style="width: 180px;" v-model="loginUser.code_1" placeholder="请输入验证码" />
            <!-- <template v-slot="suffix"> -->
            <div class="codePicture" @click="refreshCode">
              <CanvasCode class="codePicture1" :identifyCode="codeData.identifyCode"></CanvasCode>
            </div>
          </div>

          <!-- </template> -->
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" @click="handleLogin(loginForm)">登录</el-button>
        </div>
      </el-form>
    </div>
    <el-drawer v-model="drawer" title="可测试的账号">
      <div class="drawer-main">
        <p class="drawer-p">管理员：<span>
            admin@admin.com
          </span></p>
        <p class="drawer-p">求职者：<span>
            a1@a.com
          </span></p>
        <p class="drawer-p">招聘者：<span>
            h1@h.com
          </span></p>
        <p class="drawer-p">默认密码：<span>
            123456
          </span></p>
      </div>
    </el-drawer>
  </div>
</template>
<script lang='ts' setup>
import { reactive, getCurrentInstance, ref, onBeforeMount } from 'vue'
import { data, elmessage } from "@/hook/hook"
import { useRoute, useRouter } from 'vue-router';
import { loginUser, loginRules } from "@/utills/loginValidators";
import Header from "@/components/Header.vue";
import { ElMessage } from 'element-plus';
import { useStore } from "vuex"
import type { FormInstance } from 'element-plus'
import { login, loginOu } from "@/api/authApi"
// export default {
//   name: "Login",
//   setup() {

//创建store对象
const store = useStore()
// 登录
// @ts-ignore
const { proxy } = getCurrentInstance() // 1.获取proxy实例

// 登录表单
const loginForm = ref<FormInstance>();

const router = useRouter()
// 测试账号
const drawer = ref(false)
const handleFold = () => {
  drawer.value = true

}
const codeData = reactive({
  identifyCodes: '1234567890abcdefjhijk1234567890linopqrsduvwxyz', // 验证码组成元素
  identifyCode: '', // 验证码生成结果
  code: '', // 验证码输入内容
})
// 重置验证码
const refreshCode = () => {
  codeData.identifyCode = ''
  makeCode(codeData.identifyCodes, 4)
  loginUser.code_2 = codeData.identifyCode
  // console.log(data.identifyCode);

}
const makeCode = (o: any, l: any) => {
  // o代表随机数元素集合，l代表验证码位数（现在为4位验证码）
  for (let i = 0; i < l; i++) {
    codeData.identifyCode += codeData.identifyCodes[randomNum(0, codeData.identifyCodes.length)]
  }

}
const randomNum = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min) + min)
}
// 删除登录记录，在某人未退出的状态，另一人就直接登录，则需要将后台redis登录记录删除
const delloginlog = () => {

  if (data().loginId) {
    loginOu(data())
    store.commit("loginOut")
    localStorage.removeItem("loginData")
  }
}

// 触发登录方法  async异步
const handleLogin = async (form: FormInstance | undefined) => {
  if (!form) return
  // 点击按钮触发表单验证
  form.validate((valid: any) => {

    if (valid) {
      // 表单数据解构成字典
      const data = {
        email: loginUser.email,
        password: loginUser.password,
        role: "admin"
      }
      login(data).then(
        (res: any) => {
          if (res.data["code"] === "200") {
            // 注册成功跳转主页
            elmessage(res.data["message"], res.data["type"])
            // 清除之前的登录记录
            delloginlog()
            // 本地存储登录状态
            localStorage.setItem("loginData", JSON.stringify({ "loginId": res.data.loginId, "token": res.data.token, "identity": res.data.identity }))

            store.commit("loginState", res.data)
            setTimeout(() => {
              router.push("/adminhome")
            }, 500);

          }
          else {

            elmessage(res.data["message"], res.data["type"])
            return false
          }
        }

      )
      form.resetFields()
    } else {
      return false;
    }
  });
};

onBeforeMount(() => {
  refreshCode()
})
//     return {
//       loginUser,
//       loginRules,
//       loginForm,
//       codeData,
//       refreshCode,
//       handleLogin,
//     };
//   },
//   components: { Header }
// }
</script>
<style lang="css" scoped>
.drawer-p {
  height: 32px;
  width: 100%;
}

.drawer-main {
  /* display: flex; */
  height: 100%;
  width: 100%;
}

.fold-icon {

  float: right;
  margin-right: 50px;
  margin-top: 50px;
}

.fold-icon:hover {

  cursor: pointer;
}

a {
  text-decoration: none;
}

a:hover {
  text-decoration: underline !important;
}

.login-wrap {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-size: cover;
  background-image: url("../../assets/loginRegister/adminLoginBg.jpeg");

}

.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #000;
  border-bottom: 1px solid #ddd;
}

.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}

.ms-content {
  padding: 30px 30px;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}

.codeItem {
  width: 310px;
  /* display: inline-flex; */
  float: auto;
}

.codePicture {
  width: 100px;
  height: 30px;
  text-align: center;
  float: right;
  /* margin-left: 4px; */
  /* margin: 5px 30px; */
  border: 2px solid #009199;
}

.codePicture1 {
  float: right;
  width: 100px;
  height: 30px;
}
</style>